<?php

class UsuariosModel
{
    function __construct($db)
	{
        try {
            $this->db = $db;
        } catch (PDOException $e) {
            exit('Database connection could not be established.');
        }
    }
	
	public function consultaEmailExiste($email)
	{		
		$sql = "SELECT COUNT(email) as qtd_email FROM usuario WHERE email= :email";
		$query = $this->db->prepare($sql);
		$query->execute(array(':email'=>$email));
		return $query->fetch();
	}

	public function verificaContaExiste($email, $senha)
	{

		$sql = "SELECT COUNT(id) AS qtd FROM usuario WHERE email = :email AND senha = :senha";
        $query = $this->db->prepare($sql);
        $query->execute(array(':email'=>$email, ':senha'=>$senha));
        
        $logado = false;

        if($query->fetch()->qtd == 1)
        	$logado = true;

        return $logado;
	}
	
	public function consultaUsuario($email, $senha)
	{

		$sql = "SELECT * FROM usuario WHERE email = :email AND senha = :senha";
        $query = $this->db->prepare($sql);
        $query ->execute(array(':email'=>$email, ':senha'=>$senha));

        return $query->fetch();
	}
	
	public function consultaUsuarioPorId($id)
	{
		$sql = "SELECT id, nome, datanasc, email, senha FROM usuario WHERE id = :id";
		$query = $this->db->prepare($sql);
		$query->execute(array(":id" => $id));
		return $query->fetch();
	}
	
	public function alteraUsuarioPorId($valores)
	{
		$sql = "UPDATE usuario SET nome = :nome, datanasc = :datanasc, email = :email, senha=:senha WHERE id = :id";
		$query = $this->db->prepare($sql);
		$query->execute(array(
			':id' => $valores['id'],
			':nome' => $valores['nome'], 
			':datanasc' => $valores['datanasc'],
			':email' => $valores['email'], 
			':senha' => $valores['senha']
		));
	}
	
	public function adiciona($valores) 
	{    		
        $sql = "INSERT INTO usuario (nome, datanasc, email, senha, tipous) VALUES (:nome, :datanasc, :email, :senha, :tipous)";
        $query = $this->db->prepare($sql);
        $query->execute(array(
			':nome' => $valores['nome'], 
			':datanasc' => $valores['datanasc'],
			':email' => $valores['email'], 
			':senha' => $valores['senha'],
			':tipous' => $valores['tipous']
		));
    }
	
}